/* 
    【1】面向过程写代码
        【1】获取元素
        【2】获取数据
        【3】渲染
        【4】点击事件的操作 + - 删除 结算
    【2】面向对象写代码
        【1】创建对象
            class Cart{}
        【2】描述对象
            +   静态属性
                +   ele 购物车的容器
                +   用户名 哪个用户的购物车
            +   动态方法
                +   获取数据
                +   渲染数据
                +   计算总价 和商品数量
                +   修改商品
                +   删除商品
                +   清空购物车
        【3】使用对象
            new Cart();
*/
window.onload = function () {
    function fun() {
        console.log(80);
        class Cart {
            constructor(ele, login) {
                this.ele = document.querySelector(ele);
                this.user = login;

                this.init();
            }
            init() {
                this.content = this.ele.querySelector(".content");
                this.goodsType = this.ele.querySelector(".goodsType");
                this.goodsQty = this.ele.querySelector(".goodsQty");
                this.goodsPrice = this.ele.querySelector(".goodsPrice");
                this.allChecked = this.ele.querySelector(".allChecked");
                this.getDate();

                // 利用事件委托的形式给购物车中的元素绑定点击事件
                this.ele.onclick = (e) => {
                    var e = e || window.event;
                    if (e.target.classList.contains("allChecked")) {
                        this.data = JSON.parse(localStorage.getItem("data"));
                        console.log(this.data);
                        // 当勾选全选按钮的时候 item.is_select = '1',不选择的时候 item.is_select = '0'
                        // checked = true 表示选中
                        // checked = false 表示不选中
                        this.data.forEach((item) => {
                            item.is_select = e.target.checked ? "1" : "0";
                        });

                        localStorage.setItem("data", JSON.stringify(this.data));
                        this.calculation();
                        this.render();
                    }

                    // 单选
                    if (e.target.classList.contains("checked")) {
                        let id = e.target.getAttribute("data_id");
                        this.data = JSON.parse(localStorage.getItem("data"));
                        this.data.forEach((item) => {
                            if (item.goods_id == id) {
                                item.is_select = e.target.checked ? "1" : "0";
                            }
                        });
                        let flag = this.data.every((item) => {
                            return item.is_select == "1";
                        });
                        this.allChecked.checked = flag;
                        localStorage.setItem("data", JSON.stringify(this.data));
                        this.calculation();
                        this.render();
                    }

                    if (e.target.classList.contains("btn-delete")) {
                        let id = e.target.getAttribute("data_id");
                        this.removeData(id);
                    }

                    if (e.target.classList.contains("reduce")) {
                        let id = e.target.parentNode.getAttribute("data_id");
                        let num = e.target.nextElementSibling.innerText * 1; //获取下一个兄弟元素的文本，注意是兄弟元素
                        num--;
                        this.updata(id, num);
                    }

                    if (e.target.classList.contains('add')) {
                        let id = e.target.parentNode.getAttribute("data_id");
                        let num = e.target.previousElementSibling.innerText * 1; //获取上一个兄弟元素的文本
                        num++;
                        this.updata(id, num);
                    }
                    // ajax({
                    //     url: "../api/regist.php",
                    //     type: "get",
                    //     data: {
                    //         username: registUser.value,
                    //         password: registPass.value,
                    //     },
                    //     success: function (res) {
                    //         console.log(res);
                    //     }
                    // });写着是干啥？
                };
            }

            async getDate() {
                let res = await pAjax({
                    url: "../api/getCarData.php",
                    data: {
                        username: this.user
                    },
                });
                // !!!把获取出来的数据 存到本地存储中，一些状态的改变 直接改变本地存储中的数据，而不是直接改变数据库中数据,(这就是为什么点击添加购物车就可以把对应数据渲染上取)
                localStorage.setItem("data", res);

                console.log(res);
                this.data = JSON.parse(res);
                // console.log(2);
                console.log(this.data);

                this.calculation();
                this.render();
            }

            render() {
                this.content.innerHTML = this.data
                    .map((item) => {
                        return `<div class="media">
                <div class="media-left media-middle">
                    <input type="checkbox" data_id="${
                        item.goods_id
                    }"  class="checked" ${
                    item.is_select == "1" ? "checked" : ""
                }/>
                    <a href="#">
                        <img
                            class="media-object"
                            src="${item.ba}"
                            alt="..."
                        />
                    </a>
                </div>
                <div class="media-body">
                    <h4 class="media-heading">${item.er}</h4>
                    <p class="price">
                        <span
                            class="glyphicon glyphicon glyphicon-jpy"
                            aria-hidden="true"
                        ></span>
                        <span>${item.san}</span>
                    </p>
                    <div class="btns">
                        <button data_id=" ${
                            item.goods_id
                        }" class="btn btn-danger btn-delete btn-sm">删除商品</button>


                        <div class="btn-group" data_id="${
                            item.goods_id
                        }" role="group">
                            <button
                                type="button"
                                class="btn reduce ${
                                    item.cart_number == 1 ? "disabled" : ""
                                } btn-sm btn-default" ${
                    item.cart_number == 1 ? "disabled" : ""
                }
                            >
                                -
                            </button>
                            <button
                                type="button"
                                class="btn btn-sm btn-default"
                            >
                                ${item.cart_number}
                            </button>
                            <button
                                type="button"
                                class="btn add btn-sm btn-default"
                            >
                                +
                            </button>
                        </div>
                    </div>
                </div>
            </div>`;
                    })
                    .join("");
            }


            // 计算商品种类 和所选商品的数量 和价格
            calculation() {
                this.goodsType.innerHTML = this.data.length;

                // 获取本地存储中的数(据 来判断 所选商品的数量 和 价格
                let data = JSON.parse(localStorage.getItem("data"));
                console.log(data);
                this.goodsQty.innerHTML = data.reduce((pre, item) => {
                    if (item.is_select == "1") {
                        return pre + item.cart_number * 1;
                    }
                    return pre;
                }, 0);

                let goodsPriceTxt = data.reduce((pre, item) => {
                    if (item.is_select == "1") {
                        return pre + item.san * item.cart_number;
                    }
                    return pre;
                }, 0);
                this.goodsPrice.innerHTML = goodsPriceTxt.toFixed(2);
            }

            async removeData(id) {
                let res = await pAjax({
                    url: "../api/removeCarData.php",
                    data: {
                        username: this.user,
                        goods_id: id,
                    },
                });
                // 当把数据库中的数据删除成功之后 需要把本地存储的数据也删掉
                res = JSON.parse(res);
                if (!res.code) {
                    alert("删除失败");
                    return;
                }

                this.data = JSON.parse(localStorage.getItem("data"));

                this.data = this.data.filter((item) => {
                    return item.goods_id != id * 1;
                });

                localStorage.setItem("data", JSON.stringify(this.data));
                this.render();
            }

            async updata(id, num) {
                let res = await pAjax({
                    url: "../api/updCarData.php",
                    data: {
                        username: this.user,
                        goods_id: id,
                        goods_num: num,
                    },
                });

                res = JSON.parse(res);
                if (!res.code) return;
                this.data = JSON.parse(localStorage.getItem("data"));
                this.data.forEach((item) => {
                    if (item.goods_id == id) {
                        item.cart_number = num;
                    }
                });

                localStorage.setItem("data", JSON.stringify(this.data));
                this.render();
            }
        }
        // console.log(data);

        let login = getCookie("login");

        if (!login) {
            localStorage.setItem("url", location.href);
            location.href = "../login/login.html";
        }
        new Cart(".container", login);
    }
    fun();
}